package com.caird.pmp.iot.handler.impl;

import com.caird.pmp.iot.entity.DeviceShadow;
import com.caird.pmp.iot.handler.HandlerBase;
import com.caird.pmp.iot.message.IMessage;
import com.caird.pmp.iot.message.impl.DeviceMessage0102;
import com.caird.pmp.iot.message.impl.ServerMessage8001;
import com.caird.pmp.iot.server.BbChannelManager;
import io.netty.channel.Channel;
import org.springframework.stereotype.Controller;

import java.util.Date;

@Controller
public class Handler0102 extends HandlerBase {

    @Override
    public boolean handle(Channel channel, IMessage message) {

        DeviceMessage0102 dm = (DeviceMessage0102)message;

        boolean success = false;

        do {
            //鉴权码验证
            if (!dm.getSimNo().equals(new StringBuffer(dm.getAuth()).reverse().toString()))
                break;

            //设备验证
            if (!cacheService.isSimNoExist(dm.getSimNo()))
                break;

            //登录失败不应答
            if (!login(channel, dm.getSimNo()))
                return false;

            success = true;

        } while (false);

        ServerMessage8001 sm;

        if (success)
            sm = ServerMessage8001.success(dm, BbChannelManager.getFlowNo(channel));
        else
            sm = ServerMessage8001.failure(dm, BbChannelManager.getFlowNo(channel));

        writeAndFlush(channel, sm.encode());

        //保存登录信息
        if (ServerMessage8001.SUCCESS == sm.getResult()) {
            DeviceShadow shadow = getShadow(dm.getSimNo());
            shadow.setLoginTime(new Date());
            shadow.setLoginCount(null == shadow.getLoginCount() ? 1 : shadow.getLoginCount() + 1);
            shadow.clockIn();
            setShadow(dm.getSimNo(), shadow);
        }

        return true;
    }
}
